<?php

/**
 * This is the model class for table "{{cafeownersubscribe}}".
 *
 * The followings are the available columns in table '{{cafeownersubscribe}}':
 * @property integer $id
 * @property integer $shopId
 * @property string $txn_id
 * @property integer $startDate
 * @property integer $endDate
 *
 * The followings are the available model relations:
 * @property McrjoPaymenttransaction $txn
 * @property Coffeeshop $shop
 */
class CafeOwnerSubscribe extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return CafeOwnerSubscribe the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{cafeownersubscribe}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
		array('shopId, startDate, endDate', 'required'),
		array('shopId, startDate, endDate', 'numerical', 'integerOnly'=>true),
		array('startDate','checkValidSubscription', 'on'=>'insert'),
		array('shopId','checkFutureSubscriptionExists', 'on'=>'insert'),
		array('endDate','compareStartEndDate'),
		array('txn_id', 'length', 'max'=>64),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('id, shopId, txn_id, startDate, endDate', 'safe', 'on'=>'search'),
		array('id, shopId, txn_id, startDate, endDate', 'safe', 'on'=>'ipn'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'txn' => array(self::HAS_ONE, 'MCRPaypalTransaction', 'txn_id'),
			'shop' => array(self::BELONGS_TO, 'CoffeeShop', 'shopId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'shopId' => 'Shop',
			'txn_id' => 'Txn',
			'startDate' => 'Start Date',
			'endDate' => 'End Date',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		/*
		$criteria->compare('id',$this->id);
		$criteria->compare('shopId',$this->shopId);
		$criteria->compare('txn_id',$this->txn_id,true);
		$criteria->compare('startDate',$this->startDate);
		$criteria->compare('endDate',$this->endDate);
		*/
		$criteria->with = array('shop'=>array('condition'=>'name LIKE "%'.$this->shopId.'%"'));
		$criteria->order = 't.id DESC';

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * @param param params passed from Yii::app()->user->checkAccess()
	 */
	public static function isSubscribedToCafe($param){
		if(!Yii::app()->user->checkAccess('authenticated')){
			return false;
		}
		if(!isset($param['shop'])){
			throw new CHttpException(404,"Shop not specified");
		}
		$shop=$param['shop'];
		if(!is_object($shop)){
			$shop=CoffeeShop::model()->findByPk(intval($shop));
			if(empty($shop)){
				throw new CHttpException(404,"Shop ".$param['shop']." does not exist!");
			}
		}
		$userId=Yii::app()->user->id;
		if($shop->ownerId!=$userId){
			return false;
		}
		if($shop->premiumAccess){
			return true;
		}
		$now=time();
		$criteria=new CDbCriteria;
		$criteria->compare('shopId',$shop->id);
		$criteria->compare('startDate','<='.$now);
		$criteria->compare('endDate','>='.$now);
		$subscribe=CafeOwnerSubscribe::model()->find($criteria);
		if(!empty($subscribe)){
			return true;
		}
		return false;
	}
	
	/**
	 * Validtion function to check if the end date is ealier thatn start date.
	 * @param unknown_type $attribute
	 * @param unknown_type $params
	 */
	public function compareStartEndDate($attribute,$params){
		if ($this->startDate >= $this->endDate)
			$this->addError('endDate', 'Start Date should be earlier than End Date');
	}
	
	/**
	 * Validation function to check if the new subscription is not valid - that means:
	 * 1. there is a subscription for the shop.
	 * 2. and the start date of new subscription is earlier than the end date of the old
	 * subscription.
	 * @param unknown_type $attribute
	 * @param unknown_type $params
	 */
	public function checkValidSubscription($attribute,$params){
		$subscription = self::model()->find(array(
			'condition'=>'shopId = :shopId AND startDate <= UNIX_TIMESTAMP(NOW()) AND endDate >= UNIX_TIMESTAMP(NOW())',
			'params'=>array(':shopId'=>$this->shopId)
		));
		
		if($subscription && ($subscription->endDate >= $this->startDate)){
			$this->addError('startDate', 'The start date of new subscription should be after '
				.date('d/m/Y',$subscription->endDate)
				.' the end date of the old subscription.');
		}
	}
	
	/**
	 * Validation function to check if there is a future subscription.
	 * @param unknown_type $attribute
	 * @param unknown_type $params
	 */
	public function checkFutureSubscriptionExists($attribute,$params){
		$subscription = self::model()->find(array(
			'condition'=>'shopId = :shopId AND startDate <= UNIX_TIMESTAMP(NOW()) AND endDate >= UNIX_TIMESTAMP(NOW())',
			'params'=>array(':shopId'=>$this->shopId)
		));
		
		if (empty($subscription))
			return;

		// check if there is already a future subscription.
		$futureSubscriptionExists = self::model()->exists(array(
			'condition'=>'shopId = :shopId AND startDate > :currentSubEndDate',
			'params'=>array(':shopId'=>$this->shopId,':currentSubEndDate'=>$subscription->endDate)
		));
		
		if ($futureSubscriptionExists){
			$this->addError('shopId', 'The shop already has a future subscription and you can not add a new one');
		}
	}
}